// WalletServiceImpl.java - 修改后的Service实现类
package com.elm.service.impl;

import com.elm.mapper.UserMapper;
import com.elm.mapper.WalletMapper;
import com.elm.domain.VirtualWallet;
import com.elm.po.Wallet;
import com.elm.po.Transaction;
import com.elm.service.WalletService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WalletServiceImpl implements WalletService {

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserMapper userMapper;

    private String getCurrentUserName() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUsernameFromToken(token);
    }

    private int getCurrentUserId() {
        return userMapper.getUserIdByName(getCurrentUserName());
    }

    // 获取钱包领域对象
    private VirtualWallet getVirtualWallet() {
        int userId = getCurrentUserId();
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null) {
            walletMapper.createWallet(userId);
            wallet = walletMapper.getWalletByUserId(userId);
        }
        return convertToDomain(wallet);
    }

    // PO转领域对象
    private VirtualWallet convertToDomain(Wallet wallet) {
        VirtualWallet virtualWallet = new VirtualWallet();
        virtualWallet.setId(wallet.getId());
        virtualWallet.setUserId(wallet.getUserId());
        virtualWallet.setBalance(wallet.getBalance());
        virtualWallet.setFrozen(wallet.getFrozen());
        virtualWallet.setOverdraft(wallet.getOverdraft());
        virtualWallet.setConsumption(wallet.getConsumption());
        virtualWallet.setVip(wallet.getVip());
        virtualWallet.setCreatedAt(wallet.getCreatedAt());
        virtualWallet.setUpdatedAt(wallet.getUpdatedAt());
        return virtualWallet;
    }

    // 领域对象转PO
    private Wallet convertToPO(VirtualWallet virtualWallet) {
        Wallet wallet = new Wallet();
        wallet.setId(virtualWallet.getId());
        wallet.setUserId(virtualWallet.getUserId());
        wallet.setBalance(virtualWallet.getBalance());
        wallet.setFrozen(virtualWallet.getFrozen());
        wallet.setOverdraft(virtualWallet.getOverdraft());
        wallet.setConsumption(virtualWallet.getConsumption());
        wallet.setVip(virtualWallet.getVip());
        wallet.setCreatedAt(virtualWallet.getCreatedAt());
        wallet.setUpdatedAt(virtualWallet.getUpdatedAt());
        return wallet;
    }

    // 保存领域对象状态到数据库
    private void saveVirtualWallet(VirtualWallet virtualWallet) {
        Wallet wallet = convertToPO(virtualWallet);
        // 这里需要添加更新wallet的方法到WalletMapper
        walletMapper.updateWallet(wallet);
    }

    @Override
    public Wallet getWallet() {
        VirtualWallet virtualWallet = getVirtualWallet();
        return convertToPO(virtualWallet);
    }

    @Override
    @Transactional
    public int recharge(Double amount) {
        VirtualWallet virtualWallet = getVirtualWallet();

        // 使用领域对象的业务方法
        virtualWallet.recharge(amount);

        // 保存状态并记录流水
        saveVirtualWallet(virtualWallet);
        walletMapper.insertTransaction(0, 0, virtualWallet.getUserId(), amount, 0.0, "recharge", "充值");

        return 1;
    }

    @Override
    @Transactional
    public int withdraw(Double amount) {
        VirtualWallet virtualWallet = getVirtualWallet();

        // 使用领域对象的业务方法
        virtualWallet.withdraw(amount);

        // 保存状态并记录流水
        saveVirtualWallet(virtualWallet);
        walletMapper.insertTransaction(0, virtualWallet.getUserId(), 0, amount, 0.0, "withdraw", "提现");

        return 1;
    }

    @Override
    @Transactional
    public int transfer(int fromUserId, int toUserId, Double amount, String remark) {
        // 获取转出方钱包
        Wallet fromWalletPO = walletMapper.getWalletByUserId(fromUserId);
        VirtualWallet fromWallet = convertToDomain(fromWalletPO);

        // 获取转入方钱包
        Wallet toWalletPO = walletMapper.getWalletByUserId(toUserId);
        if (toWalletPO == null) {
            walletMapper.createWallet(toUserId);
            toWalletPO = walletMapper.getWalletByUserId(toUserId);
        }
        VirtualWallet toWallet = convertToDomain(toWalletPO);

        // 执行业务逻辑
        fromWallet.withdraw(amount);
        toWallet.recharge(amount);

        // 保存状态
        saveVirtualWallet(fromWallet);
        saveVirtualWallet(toWallet);

        // 记录交易流水
        return walletMapper.insertTransaction(0, fromUserId, toUserId, amount, 0.0, "transfer", remark);
    }

    @Override
    public List<Transaction> getTransactions() {
        int userId = getCurrentUserId();
        int walletId = walletMapper.getWalletIdByUserId(userId);
        return walletMapper.getTransactions(walletId);
    }

    @Override
    @Transactional
    public int repay(double amount) {
        VirtualWallet virtualWallet = getVirtualWallet();

        // 还款逻辑：先扣减余额，再恢复透支额度
        virtualWallet.withdraw(amount);
        virtualWallet.repay(amount);

        // 保存状态并记录流水
        saveVirtualWallet(virtualWallet);
        walletMapper.insertTransaction(0, virtualWallet.getUserId(), 0, amount, 0.0, "repay", "还款");

        return 1;
    }

    // 新增方法：支付订单（使用充血模型）
    @Transactional
    public int payOrder(int orderId, Double amount) {
        VirtualWallet virtualWallet = getVirtualWallet();

        // 使用领域对象的支付方法
        virtualWallet.pay(amount);

        // 冻结金额（资金安全）
        virtualWallet.freeze(amount);

        // 保存状态
        saveVirtualWallet(virtualWallet);

        // 记录交易流水
        return walletMapper.insertTransaction(orderId, virtualWallet.getUserId(), 0, amount, 0.0, "payment", "订单支付");
    }

    // 新增方法：完成订单（使用充血模型）
    @Transactional
    public int completeOrder(int orderId) {
        Transaction transaction = walletMapper.getTransactionByOrder(orderId);
        if (transaction == null) {
            throw new IllegalStateException("未找到对应的支付记录");
        }

        Double amount = transaction.getBalanceAmount();
        int userId = transaction.getFromId();

        // 获取商家钱包（这里简化处理，实际应该根据订单获取商家ID）
        Wallet merchantWalletPO = walletMapper.getWalletByUserId(userId);
        VirtualWallet merchantWallet = convertToDomain(merchantWalletPO);

        // 商家解冻金额
        merchantWallet.unfreeze(amount);

        // 更新用户消费金额和VIP等级
        VirtualWallet userWallet = getVirtualWallet();
        userWallet.addConsumption(amount);

        // 保存状态
        saveVirtualWallet(merchantWallet);
        saveVirtualWallet(userWallet);

        return 1;
    }
}